import React from 'react'
import { ArrowRightOutlined, DeleteOutlined, PlusOutlined, QuestionCircleOutlined } from '@ant-design/icons'
import { Form } from '@ant-design/compatible'
import '@ant-design/compatible/assets/index.css'
import { getTagList } from '@/services/tag'
import {
  Input,
  Select,
  Button,
  notification,
  Modal,
  Tag,
  Tooltip,
  Row,
  Col,
  Card,
  Upload,
  Steps,
  Radio,
  message,
} from 'antd'
import { getInfo, editInfo, uploadConfigFile } from '@/services/dataCenter'
import { relationRedo, getInputRelations, relationNotExists, checkBeforeFileUpload } from '@/utils/utils'
import { getVersionList } from '@/services/modelCenter'
import styles from '../style.less'

const FormItem = Form.Item
const { Option } = Select
const containSpecial = new RegExp("[%--`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]")
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 5 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 19 },
  },
}
const { Step } = Steps
let pageSize = 10
let pageSizeProps = 10
class Edit extends React.Component {
  constructor(argus) {
    super(argus)

    this.state = {
      id: '',
      type: 0, //0：实体 3关键词 1：关系 4:属性  5：事件
      isProp: false,
      isEvent: false, // 事件标注
      loading: false,
      objectLabels: [], // 标签
      propLabels: [], // 属性标签
      relations: [], // 关系
      inputVisible: false,
      inputPropVisible: false,
      inputValue: '', // 标签新增时 输入的内容
      inputPropValue: '', // 属性标签新增时 输入的内容
      labelToNameList: [], // 某一个关系的 目标实体
      labelFromNameList: [], // 某一个关系的 起始实体
      labelFromName: undefined, // 某一个关系的 起始实体
      labelRelationName: '', // 某一个关系的 关系
      labelled: 0, // 是否已标注,
      fileList: [], // 上传文件成员
      current: 0, // 配置映射 当前步骤
      versionList: [], // 模型列表,
      usePreLabel: '0', // 预标注模型 0 不进行 1 进行
      preLabelVersionId: undefined, // 选择预标注模型
      usePreLabelRule: '0', // 预标注规则
      searchMessages: [], //搜索结果
      searchValue: '',
      searchMessagesProps: [], //搜索结果
      searchValueProps: '',
    }
  }

  componentDidMount() {
    const { id, type, labelled } = this.props
    this.setState({ isProp: type === 4, isEvent: type === 5 })
    this.queryData(id, type, labelled)
    this.queryVersionList()
  }

  checkCommonRelation(relationList) {
    return relationList.filter(
      (item) =>
        this.state.relations.filter(
          (rel) =>
            rel.labelRelationId === item.labelRelationId ||
            (rel.labelFromName === item.labelFromName &&
              rel.labelRelationName === item.labelRelationName &&
              rel.labelToName === item.labelToName),
        ).length === 0,
    )
  }

  // 获取配置信息
  queryData(id, type) {
    getInfo(id, type).then((res) => {
      if (res.retCode === '0') {
        this.setState({ id, type })
        if (type - 0 === 1) {
          // 关系配置
          const relationList = res.data.relationLabelList.map((relation) => {
            relation.isSave = true
            return relation
          })
          this.setState({
            objectLabels: this.state.objectLabels.concat(
              res.data.objectLabelList.filter(
                (item) =>
                  this.state.objectLabels.filter(
                    (obj) => obj.labelId === item.labelId || obj.labelName === item.labelName,
                  ).length === 0,
              ),
            ),
          })
          this.setState({ relations: this.state.relations.concat(this.checkCommonRelation(relationList)) })
        } else if (type - 0 === 4) {
          // 属性关系配置
          const relationList = res.data.relationLabelList.map((relation) => {
            relation.isSave = true
            return relation
          })
          this.setState({
            objectLabels: this.state.objectLabels.concat(
              res.data.objectLabelList.filter(
                (item) =>
                  this.state.objectLabels.filter(
                    (obj) => obj.labelId === item.labelId || obj.labelName === item.labelName,
                  ).length === 0 && item.labelType === 0,
              ),
            ),
          })
          this.setState({
            propLabels: this.state.propLabels.concat(
              res.data.objectLabelList.filter(
                (item) =>
                  this.state.propLabels.filter(
                    (obj) => obj.labelId === item.labelId || obj.labelName === item.labelName,
                  ).length === 0 && item.labelType === 1,
              ),
            ),
          })
          this.setState({ relations: this.state.relations.concat(this.checkCommonRelation(relationList)) })
        } else if (type - 0 === 5) {
          // 事件抽取配置
          const relationList = res.data.relationLabelList.map((relation) => {
            relation.isSave = true
            return relation
          })
          //
          this.setState({
            objectLabels: this.state.objectLabels.concat(
              res.data.objectLabelList.filter(
                (item) =>
                  this.state.objectLabels.filter(
                    (obj) => obj.labelId === item.labelId || obj.labelName === item.labelName,
                  ).length === 0 && item.labelType === 0,
              ),
            ),
          })
          this.setState({
            propLabels: this.state.propLabels.concat(
              res.data.objectLabelList.filter(
                (item) =>
                  this.state.propLabels.filter(
                    (obj) => obj.labelId === item.labelId || obj.labelName === item.labelName,
                  ).length === 0 && item.labelType === 1,
              ),
            ),
          })
          this.setState({ relations: this.state.relations.concat(this.checkCommonRelation(relationList)) })
        } else {
          // 其他单标签形式配置labelName C35Law
          // 导入标签配置后接口会将所有的标签都返回，就会导致之前添加的标签重复出现，故做过滤，合并后将新增的与旧的展示在页面上
          this.setState({
            objectLabels: this.state.objectLabels.concat(
              res.data.objectLabelList.filter(
                (item) =>
                  this.state.objectLabels.filter(
                    (obj) => obj.labelId === item.labelId || obj.labelName === item.labelName,
                  ).length === 0,
              ),
            ),
          })
        }
        this.setState({
          preLabelVersionId: res.data.preLabelVersionId ? res.data.preLabelVersionId : this.state.preLabelVersionId,
          usePreLabel: this.state.usePreLabel !== '0' ? this.state.usePreLabel : res.data.usePreLabel.toString(),
          usePreLabelRule:
            this.state.usePreLabelRule !== '0' ? this.state.usePreLabelRule : res.data.usePreLabelRule.toString(),
        })
      }
    })
  }

  // 获取模型下的 版本列表
  queryVersionList() {
    getVersionList({ data: { modelType: this.props.type, versionStatus: 1 }, pageSize: 0, pageNum: 0 }).then((res) => {
      if (res.retCode === '0') {
        this.setState({
          versionList: res.data.list,
          preLabelVersionId:
            this.state.preLabelVersionId === undefined && res.data.list.length !== 0
              ? res.data.list && res.data.list[0].versionId
              : this.state.preLabelVersionId,
        })
      }
    })
  }

  // 提交修改的内容
  handleUserSubmit = (e) => {
    e.preventDefault()
    const that = this
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const { usePreLabel, usePreLabelRule, preLabelVersionId } = values
        const { id, objectLabels, propLabels, relations, type } = that.state
        const labelList = []
        if (objectLabels.length === 0) {
          that.props.form.setFields({
            objectLabels: {
              value: objectLabels,
              errors: [new Error('请添加标签!')],
            },
          })

          return
        }
        labelList.push(...objectLabels)
        if (type === 4) {
          if (propLabels.length === 0) {
            that.props.form.setFields({
              propLabels: {
                value: propLabels,
                errors: [new Error('请添加属性标签!')],
              },
            })
            return
          }
          labelList.push(...propLabels)
        }
        if (type === 5) {
          if (propLabels.length === 0) {
            that.props.form.setFields({
              propLabels: {
                value: propLabels,
                errors: [new Error('请添加事件标签!')],
              },
            })
            return
          }
          labelList.push(...propLabels)
        }
        if ((type === 1 || type === 4 || type === 5) && relations.length === 0) {
          type === 5 ? message.error('请添加角色映射!') : message.error('请添加关系!')
          if (type === 5) {
            that.props.form.setFields({
              relations: {
                errors: [new Error('请添加角色映射!')],
              },
            })
          } else {
            that.props.form.setFields({
              relations: {
                errors: [new Error('请添加关系!')],
              },
            })
          }
          return
        }
        that.setState({ loading: true })
        editInfo(
          {
            dataSetId: id,
            objectLabelList: labelList,
            relationLabelList: relations,
            usePreLabel,
            usePreLabelRule,
            preLabelVersionId,
          },
          type,
        )
          .then((rs) => {
            console.log('rs', rs)
            if (rs.retCode == '0') {
              notification.success({
                message: '操作成功',
                key: '操作成功',
                description: '标注标签配置成功',
              })
              that.infoToParent(false)
            } else {
              that.setState({ loading: false })
            }
          })
          .catch((err) => {
            console.log('err', err)
          })
      } else {
        console.log('err', err)
      }
    })
  }

  onInputReChange = (e) => {
    e.preventDefault()
    const inputValue = e.target.value.trim()
    // const reg = /^[\u4e00-\u9fa5]+|[a-zA-Z0-9]+$/;

    // const inputValue = this.state.inputValue.trim();
    const isContainSpecial = containSpecial.test(inputValue)
    if (isContainSpecial) {
      // if (value && reg.test(value) == false) {
      this.props.form.setFields({
        relations: {
          errors: [new Error('关系内容不允许特殊字符')],
        },
      })
      return
    }
    this.setState({ labelRelationName: e.target.value.trim() })
  }

  onSelectChange(key, val) {
    const {
      isProp,
      isEvent,
      labelToNameList,
      labelFromName,
      labelFromNameList,
      labelRelationName,
      propLabels,
      objectLabels,
    } = this.state
    if (key == 'to') {
      this.setState({ labelToNameList: val })
    } else if (key == 'from') {
      if (!(isProp || isEvent)) {
        // 非属性、事件
        this.setState({ labelFromNameList: val })
      } else {
        this.setState({ labelFromName: val })
      }
    }
    if (
      isEvent &&
      labelFromName &&
      key === 'to' &&
      (!labelRelationName ||
        (labelRelationName &&
          propLabels.filter((item) => labelFromName + item.labelName === labelRelationName).length !== 0))
    ) {
      // 先选定事件类型标签、再选择实体类型标签
      let toName = val.length > 0 ? val[0] : val
      this.setState({ labelRelationName: val.length > 0 ? labelFromName + toName : '' })
    }
    // console.log((!labelRelationName || labelRelationName && objectLabels.filter(item=> item.labelName+labelToNameList[0] === labelRelationName).length !==0))
    if (
      isEvent &&
      labelToNameList.length > 0 &&
      key === 'from' &&
      (!labelRelationName ||
        (labelRelationName &&
          objectLabels.filter((item) => item.labelName + labelToNameList[0] === labelRelationName).length !== 0))
    ) {
      // 先选定实体类型标签、再选择事件类型标签
      console.log(val + labelToNameList[0])
      this.setState({ labelRelationName: val + labelToNameList[0] })
    }
  }

  infoToParent(key) {
    this.props.callBack(key)
  }

  // 暂存 添加的关系
  saveRelation = () => {
    const { objectLabels, relations, labelToNameList, labelFromName, isProp, propLabels, isEvent } = this.state
    let { labelRelationName, labelFromNameList } = this.state
    let labelMessage = '关系，起始标签和目标标签不能为空'
    let relationMessage = '关系已存在'
    if (isProp) {
      labelRelationName = '属性'
      labelFromNameList = [labelFromName]
      labelMessage = '实体标签，属性标签不能为空'
      relationMessage = '实体属性映射已存在'
    }
    if (isEvent) {
      labelFromNameList = labelFromName ? [labelFromName] : []
      labelMessage = '角色名称，事件类型标签，实体类型标签不能为空'
      relationMessage = '角色映射已存在'
    }
    if (labelToNameList.length === 0 || labelFromNameList.length === 0 || labelRelationName == '') {
      notification.error({
        message: '添加失败',
        key: labelMessage,
        description: labelMessage,
      })
      return
    }

    if (relationNotExists(objectLabels, propLabels, labelFromNameList, labelToNameList, isProp || isEvent)) {
      notification.error({
        message: '添加失败',
        key: isProp ? '实体标签，属性标签不存在' : '事件类型标签，实体类型标签不存在',
        description: isProp ? '实体标签，属性标签不存在' : '事件类型标签，实体类型标签不存在',
      })
      this.setState({ labelFromNameList: [], labelToNameList: [], labelFromName: undefined })
      return
    }
    const inputRelations = getInputRelations(labelFromNameList, labelToNameList, labelRelationName)
    if (relationRedo(relations, inputRelations)) {
      notification.warning({
        message: '添加失败',
        key: relationMessage,
        description: relationMessage,
      })
      return
    }
    relations.push(...inputRelations)
    this.setState({ relations, labelToNameList: [], labelFromNameList: [], labelFromName: '', labelRelationName: '' })
  }

  // 暂存 删除关系
  delRelation(index) {
    const { relations } = this.state
    relations.splice(index, 1)
    this.setState({ relations })
  }

  // 暂存 删除事件
  delEvent(labelFromName, labelToNameString) {
    const { relations } = this.state
    const itemsArray = []
    const newRelations = []
    labelToNameString.split('/').map((label) => {
      itemsArray.push(labelFromName + label)
    })
    relations.map((val, index) => {
      if (itemsArray.indexOf(val.labelFromName + val.labelToName) === -1) {
        newRelations.push(val)
      }
    })
    this.setState({ relations: newRelations })
  }

  /*
   * 新增标签   开始
   */
  handleClose = (removedTag) => {
    const objectLabels = this.state.objectLabels.filter((tag) => tag.labelName !== removedTag)
    this.setState({ objectLabels })
  }

  /*
   * 新增标签   开始
   */
  handlePropClose = (removedTag) => {
    const propLabels = this.state.propLabels.filter((tag) => tag.labelName !== removedTag)
    this.setState({ propLabels })
  }

  showInput = () => {
    //TODO:showinput
    this.setState({ inputVisible: true }, () => this.input.focus())
  }

  showInputProp = () => {
    this.setState({ inputPropVisible: true }, () => this.input.focus())
  }

  handleInputChange = (e) => {
    //TODO:handleInputChange
    console.log('change', e)
    this.setState({ inputValue: e })
  }
  onSearch = async (value) => {
    if (value !== '') {
      this.setState({ inputValue: value })
    }
    const res = await getTagList({
      pageNum: 0,
      pageSize: 10,
      data: { labelName: value, labelType: 1, showDetail: false },
    })
    console.log(res)
    this.setState({
      searchMessages: res.data.list,
    })
    this.setState({
      searchValue: value,
    })
  }
  onSearchProps = async (value) => {
    if (value !== '') {
      this.setState({ inputPropValue: value })
    }
    const res = await getTagList({
      pageNum: 0,
      pageSize: 10,
      data: { labelName: value, labelType: 0, showDetail: false },
    })
    console.log(res)
    this.setState({
      searchMessagesProps: res.data.list,
    })
    this.setState({
      searchValueProps: value,
    })
  }

  handleInputPropChange = (e) => {
    console.log('change', e)
    this.setState({ inputPropValue: e })
  }

  handleInputConfirm = () => {
    const inputValue = this.state.inputValue.trim()
    const isContainSpecial = containSpecial.test(inputValue)
    if (isContainSpecial) {
      this.props.form.setFields({
        objectLabels: {
          errors: [new Error('标签内容不允许特殊字符')],
        },
      })
      return
    }
    let { objectLabels } = this.state
    if (inputValue) {
      if (objectLabels.filter((val) => val.labelName === inputValue).length) {
        this.props.form.setFields({
          objectLabels: {
            errors: [new Error('标签内容重复')],
          },
        })
        return
      }
      objectLabels = [...objectLabels, { labelName: inputValue, labelType: 0 }]
    }
    this.setState({
      objectLabels,
      inputVisible: false,
      inputValue: '',
    })
  }
  thingTypeFocus = async () => {
    console.log('focus')
    const res = await getTagList({ pageNum: 0, pageSize: 10, data: { labelName: '', labelType: 1, showDetail: false } })
    console.log(res)
    this.setState({
      searchMessages: res.data.list,
    })
  }
  thingTypeFocusProps = async () => {
    console.log('focus')
    const res = await getTagList({ pageNum: 0, pageSize: 10, data: { labelName: '', labelType: 0, showDetail: false } })
    console.log(res)
    this.setState({
      searchMessagesProps: res.data.list,
    })
  }
  onPopupScroll = async (e) => {
    console.log(e)
    pageSize += 5
    const res = await getTagList({
      pageNum: 0,
      pageSize: pageSize,
      data: { labelName: this.state.searchValue, labelType: 1, showDetail: false },
    })
    console.log(res)
    this.setState({
      searchMessages: res.data.list,
    })
  }
  onPopupScrollProps = async (e) => {
    console.log(e)
    pageSizeProps += 5
    const res = await getTagList({
      pageNum: 0,
      pageSize: pageSize,
      data: { labelName: this.state.searchValueProps, labelType: 0, showDetail: false },
    })
    console.log(res)
    this.setState({
      searchMessagesProps: res.data.list,
    })
  }

  handleInputPropConfirm = () => {
    const inputValue = this.state.inputPropValue.trim()
    const isContainSpecial = containSpecial.test(inputValue)
    if (isContainSpecial) {
      this.props.form.setFields({
        propLabels: {
          errors: [new Error('标签内容不允许特殊字符')],
        },
      })
      return
    }
    let { propLabels } = this.state
    if (inputValue) {
      if (propLabels.filter((val) => val.labelName === inputValue).length) {
        this.props.form.setFields({
          propLabels: {
            errors: [new Error('标签内容重复')],
          },
        })
        return
      }
      propLabels = [...propLabels, { labelName: inputValue, labelType: 1 }]
    }
    this.setState({
      propLabels,
      inputPropVisible: false,
      inputPropValue: '',
    })
  }

  saveInputRef = (input) => (this.input = input)
  /*
   * 新增标签   结束
   */

  /**
   * 标签添加控件
   * @returns {*}
   */
  labelView(isProp, twinLabel, type) {
    const {
      propLabels,
      objectLabels,
      inputVisible,
      inputPropVisible,
      inputPropValue,
      inputValue,
      relations,
    } = this.state
    const { form, labelled } = this.props
    const { getFieldDecorator } = form

    let labelPrefix = ''
    let labelPurpose = '实体'
    let fieldDecorator = 'objectLabels'
    let labels = objectLabels
    if (isProp) {
      if (type === 4) {
        labelPrefix = '属性'
        labelPurpose = '属性'
        fieldDecorator = 'propLabels'
        labels = propLabels
      } else if (type === 5) {
        labelPrefix = '实体类型'
        labelPurpose = '实体类型'
        fieldDecorator = 'propLabels'
        labels = propLabels
      }
    } else if (twinLabel) {
      if (type === 4) {
        labelPrefix = '实体'
      } else if (type === 5) {
        labelPrefix = '事件类型'
        labelPurpose = '事件类型触发词'
      }
    }
    return (
      <Form.Item
        label={
          <>
            <span className={styles.lableRequire}>*</span>
            <Tooltip title={`用于标注${labelPurpose},字数不超过10个`}>
              {`${labelPrefix}标签`} <QuestionCircleOutlined style={{ color: '#8795A1' }} />
            </Tooltip>
          </>
        }
        {...formItemLayout}
      >
        {getFieldDecorator(fieldDecorator, {
          rules: [
            {
              // required: true,
              message: '请添加标签!',
              validator: labels && labels.length,
            },
          ],
        })(
          <div style={{ overflowY: 'auto', maxHeight: 150 }}>
            {labels &&
              labels.map((tag, index) => {
                const isLongTag = tag.labelName.length > 20
                const tagElem = (
                  <Tag
                    key={tag.labelName + index}
                    closable={
                      !(
                        (tag.labelId && Number(labelled)) ||
                        relations.filter(
                          (val) =>
                            (val.labelFromName === tag.labelName && tag.labelType === 0) ||
                            (val.labelToName === tag.labelName && tag.labelType === 1),
                        ).length
                      )
                    }
                    onClose={isProp ? () => this.handlePropClose(tag.labelName) : () => this.handleClose(tag.labelName)}
                  >
                    {isLongTag ? `${tag.labelName.slice(0, 20)}...` : tag.labelName}
                  </Tag>
                )
                return isLongTag ? <Tooltip title={tag}>{tagElem}</Tooltip> : tagElem
              })}
            {inputVisible && !isProp && (
              // <Input
              //   ref={this.saveInputRef}
              //   type="text"
              //   size="small"
              //   style={{ width: 78 }}
              //   value={inputValue}
              //   onChange={this.handleInputChange}
              //   onBlur={this.handleInputConfirm}
              //   onPressEnter={this.handleInputConfirm}
              //   maxLength={10}
              // />
              //TODO:搜索标签
              <Select
                style={{
                  width: 78,
                }}
                ref={this.saveInputRef}
                size="small"
                showSearch
                placeholder="Select a person"
                optionFilterProp="children"
                value={inputValue}
                onChange={this.handleInputChange}
                onSearch={this.onSearch}
                onBlur={this.handleInputConfirm}
                onFocus={this.thingTypeFocus}
                onPopupScroll={this.onPopupScroll}
                // filterOption={(input, option) => option.children.toLowerCase().includes(input.toLowerCase())}
              >
                {this.state.searchMessages.map((item, index) => {
                  return (
                    <Option key={item.id} value={item.labelName}>
                      {item.labelName}
                    </Option>
                  )
                })}
              </Select>
            )}

            {inputPropVisible && isProp && (
              // <Input
              //   ref={this.saveInputRef}
              //   type="text"
              //   size="small"
              //   style={{ width: 78 }}
              //   value={inputPropValue}
              //   onChange={this.handleInputPropChange}
              //   onBlur={this.handleInputPropConfirm}
              //   onPressEnter={this.handleInputPropConfirm}
              //   maxLength={10}
              // />
              <Select
                style={{
                  width: 78,
                }}
                ref={this.saveInputRef}
                size="small"
                showSearch
                placeholder="Select a person"
                optionFilterProp="children"
                value={inputPropValue}
                onChange={this.handleInputPropChange}
                onSearch={this.onSearchProps}
                onBlur={this.handleInputPropConfirm}
                onFocus={this.thingTypeFocusProps}
                onPopupScroll={this.onPopupScrollProps}
                // filterOption={(input, option) => option.children.toLowerCase().includes(input.toLowerCase())}
              >
                {this.state.searchMessagesProps.map((item, index) => {
                  return (
                    <Option key={item.id} value={item.labelName}>
                      {item.labelName}
                    </Option>
                  )
                })}
              </Select>
            )}

            {!inputVisible && !isProp && (
              <Tag onClick={this.showInput} style={{ background: '#fff', borderStyle: 'dashed' }}>
                <PlusOutlined /> 新增标签
              </Tag>
            )}
            {!inputPropVisible && isProp && (
              <Tag onClick={this.showInputProp} style={{ background: '#fff', borderStyle: 'dashed' }}>
                <PlusOutlined /> 新增标签
              </Tag>
            )}
          </div>,
        )}
      </Form.Item>
    )
  }

  /**
   * 关系添加控件
   * @returns {*}
   */
  relationView() {
    const {
      objectLabels,
      propLabels,
      relations,
      labelToNameList,
      labelFromNameList,
      labelFromName,
      labelRelationName,
      isProp,
      isEvent,
    } = this.state
    const arrayLabelFromName = []
    const labelObject = {}
    relations &&
      relations.map((item) => {
        if (arrayLabelFromName.indexOf(item.labelFromName) !== -1) {
          labelObject[item.labelFromName] = `${labelObject[item.labelFromName]}/${item.labelToName}`
        } else {
          labelObject[item.labelFromName] = item.labelToName
          arrayLabelFromName.push(item.labelFromName)
        }
      })
    const { form, labelled } = this.props
    const { getFieldDecorator } = form

    let formPurpose = '关系'
    let fieldDecorator = 'relations'
    let fromLabel = '起始标签'
    let toLabel = '目标标签'
    if (isProp) {
      // formPurpose = '属性关系';
      fieldDecorator = 'properties'
      fromLabel = '实体标签'
      toLabel = '属性标签'
    }
    if (isEvent) {
      formPurpose = '角色映射'
      fieldDecorator = 'properties'
      fromLabel = '事件类型标签'
      toLabel = '实体类型标签'
    }

    return (
      <Form.Item
        label={
          <>
            <span className={styles.lableRequire}>*</span>
            {isEvent ? formPurpose : isProp ? '实体属性映射' : `添加${formPurpose}`}{' '}
          </>
        }
        {...formItemLayout}
      >
        {getFieldDecorator(fieldDecorator, {
          rules: [
            {
              message: `请添加${formPurpose}!`,
            },
          ],
        })(
          <div>
            <Row style={{ textAlign: 'center', backgroundColor: '#f8f8f8', paddingBottom: '8px' }} gutter={16}>
              {!(isProp || isEvent) && (
                <Col span={7}>
                  <div>关系</div>
                  <Input
                    placeholder="关系名称1-32位"
                    onChange={this.onInputReChange}
                    value={labelRelationName}
                    maxLength={32}
                  />
                </Col>
              )}
              {isEvent && (
                <Col span={7}>
                  <div>角色</div>
                  <Input
                    placeholder="角色名称1-32位"
                    onChange={this.onInputReChange}
                    value={labelRelationName}
                    maxLength={32}
                  />
                </Col>
              )}
              <Col span={isProp ? 10 : 7}>
                <div>{fromLabel}</div>
                <Select
                  showSearch
                  placeholder={`选择${fromLabel}`}
                  value={isProp || isEvent ? labelFromName : labelFromNameList}
                  mode={isProp || isEvent ? 'tag' : 'multiple'}
                  optionFilterProp="children"
                  onChange={this.onSelectChange.bind(this, 'from')}
                  filterOption={(input, option) =>
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                >
                  {objectLabels &&
                    objectLabels.map((val) => (
                      <Option key={`from_${val.labelName}`} value={val.labelName}>
                        {val.labelName}
                      </Option>
                    ))}
                </Select>
              </Col>
              <Col span={isProp ? 10 : 7}>
                <div>{toLabel}</div>
                <div style={{ overflowY: 'auto', maxHeight: 150 }}>
                  <Select
                    showSearch
                    placeholder={`选择${toLabel}`}
                    optionFilterProp="children"
                    value={labelToNameList}
                    mode="multiple"
                    onChange={this.onSelectChange.bind(this, 'to')}
                    filterOption={(input, option) =>
                      option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                    }
                  >
                    {!(isProp || isEvent) &&
                      objectLabels &&
                      objectLabels.map((val) => (
                        <Option key={`to_${val.labelName}`} value={val.labelName}>
                          {val.labelName}
                        </Option>
                      ))}
                    {(isProp || isEvent) &&
                      propLabels &&
                      propLabels.map((val) => (
                        <Option key={`to_${val.labelName}`} value={val.labelName}>
                          {val.labelName}
                        </Option>
                      ))}
                  </Select>
                </div>
              </Col>
              <Col span={3} style={{ paddingTop: 40 }}>
                <a type="link" onClick={this.saveRelation}>
                  +添加
                </a>
              </Col>
            </Row>
            <div className={styles.relationBox}>
              {isProp
                ? relations &&
                  arrayLabelFromName.map((item, i) => (
                    <div className={styles.relationItem} key={i}>
                      <Card
                        size="small"
                        title={<span style={{ fontWeight: 700 }}>{isEvent ? '角色映射' : '实体属性映射'}</span>}
                        extra={
                          item.isSave && Number(labelled) ? null : (
                            <DeleteOutlined onClick={this.delEvent.bind(this, item, labelObject[item])} />
                          )
                        }
                      >
                        <Row gutter={8}>
                          <Col span={10}>{item}</Col>
                          <Col span={4}>
                            <ArrowRightOutlined />
                          </Col>
                          <Col span={10}>{labelObject[item]}</Col>
                        </Row>
                      </Card>
                    </div>
                  ))
                : relations &&
                  relations.map((val, i) => (
                    <div className={styles.relationItem} key={i}>
                      <Card
                        size="small"
                        title={<span style={{ fontWeight: 700 }}>{val.labelRelationName}</span>}
                        extra={
                          val.isSave && Number(labelled) ? null : (
                            <DeleteOutlined onClick={this.delRelation.bind(this, i)} />
                          )
                        }
                      >
                        <Row gutter={8}>
                          <Col span={10}>{val.labelFromName}</Col>
                          <Col span={4}>
                            <ArrowRightOutlined />
                          </Col>
                          <Col span={10}>{val.labelToName}</Col>
                        </Row>
                      </Card>
                    </div>
                  ))}
            </div>
          </div>,
        )}
      </Form.Item>
    )
  }

  // 下一步
  nextStep() {
    let { current } = this.state
    current += 1
    this.setState({ current })
  }

  // 上一步
  prevStep() {
    const current = this.state.current - 1
    this.setState({ current })
  }

  onPreLabelVersionIdChange(preLabelVersionId) {
    this.setState({ preLabelVersionId })
  }

  //
  usePreLabelOnchange(element) {
    // const { versionList} = this.state;
    this.setState({
      usePreLabel: element.target.value,
      // preLabelVersionId:element.target.value ==='0' && versionList.length!==0  ?  versionList[0].versionId : this.state.preLabelVersionId
    })
  }

  render() {
    const {
      loading,
      isProp,
      isEvent,
      fileList,
      current,
      versionList,
      usePreLabel,
      usePreLabelRule,
      preLabelVersionId,
    } = this.state
    const { isShowConfigModel, type } = this.props
    const props = {
      multiple: true,
      onRemove: (file) => {
        this.setState((state) => {
          const index = state.fileList.indexOf(file)
          const newFileList = state.fileList.slice()
          newFileList.splice(index, 1)
          return {
            fileList: newFileList,
          }
        })
      },
      beforeUpload: (file, fileLists) => {
        const find = fileList.find((item) => item.name === file.name)
        const isAcceptFileType = checkBeforeFileUpload(file, ['kglabel'])
        if (!isAcceptFileType.tip) {
          notification.warning({
            message: '警告',
            key: isAcceptFileType.msg,
            description: isAcceptFileType.msg,
          })
          return true
        }
        if (find) {
          notification.warning({
            message: '警告',
            key: '存在同名文件',
            description: '存在同名文件',
          })
          return true
        }
        if (fileLists.length > 5 - this.state.fileList.length) {
          notification.warning({
            message: '警告',
            key: '每次上传文件个数不超过5个',
            description: '每次上传文件个数不超过5个',
          })
          return true
        }
        this.setState(
          (state) => ({
            // objectLabels: [], propLabels: [], relations: [],
          }),
          (_) => {
            const formData = new FormData()
            formData.append('file', file)
            formData.append('dataSetId', this.state.id)
            uploadConfigFile(formData).then((res) => {
              if (res.retCode === '0') {
                notification.success({
                  message: '成功',
                  key: '导入成功',
                  description: '该配置文件已导入',
                })
              }
              const { id, type } = this.props
              this.queryData(id, type)
            })
          },
        )
        return false
      },
      fileList,
    }
    const eventTypeMap = (
      <div>
        {this.labelView(false, isProp || isEvent, type)}
        {(isProp || isEvent) && this.labelView(true, isProp, type)}

        {(type === 1 || type === 4 || type === 5) && this.relationView()}
      </div>
    )
    const { form } = this.props
    const { getFieldDecorator } = form
    const eventElementMap = (
      <div>
        <Form.Item label="预标注模型" {...formItemLayout}>
          {getFieldDecorator('usePreLabel', {
            rules: [{ required: true }],
            initialValue: usePreLabel,
          })(
            <Radio.Group onChange={this.usePreLabelOnchange.bind(this)}>
              <Radio value="1">使用</Radio>
              <Radio value="0">不使用</Radio>
            </Radio.Group>,
          )}
        </Form.Item>
        {usePreLabel === '1' && (
          <Form.Item label="选择预标注模型" {...formItemLayout}>
            {getFieldDecorator('preLabelVersionId', {
              rules: [{ required: true, message: '请选择预标注模型' }],
              initialValue:
                preLabelVersionId && versionList.filter((item) => item.versionId === preLabelVersionId).length !== 0
                  ? preLabelVersionId
                  : undefined,
            })(
              <Select placeholder="请选择预标注模型" showSearch onChange={this.onPreLabelVersionIdChange.bind(this)}>
                {/* <Select placeholder="请选择用途" showSearch onChange={this.onPurposeChange.bind(this)}> */}
                {// eslint-disable-next-line max-len
                versionList.map((val) => (
                  <Select.Option key={val.versionId} value={val.versionId}>
                    {val.modelName}
                  </Select.Option>
                ))}
              </Select>,
            )}
          </Form.Item>
        )}
        {usePreLabel === '1' &&
          preLabelVersionId &&
          versionList.length > 0 &&
          versionList.filter((item) => item.versionId === preLabelVersionId).length === 0 && (
            <section style={{ color: '#FF4D4F', margin: '-20px 0 0 156px' }}>
              *预标注使用的模型版本不存在或已下线，请重新配置
            </section>
          )}
        <Form.Item label="预标注规则" {...formItemLayout}>
          {getFieldDecorator('usePreLabelRule', {
            rules: [{ required: true }],
            initialValue: usePreLabelRule,
          })(
            <Radio.Group>
              <Radio value="1">使用</Radio>
              <Radio value="0">不使用</Radio>
            </Radio.Group>,
          )}
        </Form.Item>
      </div>
    )
    const steps = [
      {
        title: '标签配置',
        content: eventTypeMap,
      },
      {
        title: '预标注配置',
        content: eventElementMap,
      },
    ]
    return (
      <span>
        <Modal
          title="配置标注任务"
          maskClosable={false}
          visible={isShowConfigModel}
          width={800}
          onCancel={this.infoToParent.bind(this, false)}
          footer={
            type !== 3
              ? current === 0
                ? [
                    <a type="link" style={{ float: 'left' }}>
                      <Upload {...props} showUploadList={false} accept=".kglabel">
                        <span style={{ color: '#29CCB1' }}>导入配置</span>
                      </Upload>
                    </a>,
                    <Button type="primary" onClick={() => this.nextStep()}>
                      下一步
                    </Button>,
                  ]
                : [
                    <Button key="cancel" onClick={() => this.prevStep()}>
                      上一步
                    </Button>,
                    <Button key="primary" type="primary" loading={loading} onClick={this.handleUserSubmit}>
                      确定
                    </Button>,
                  ]
              : [
                  <Button key="cancel" onClick={this.infoToParent.bind(this, false)}>
                    取消
                  </Button>,
                  <Button key="primary" type="primary" loading={loading} onClick={this.handleUserSubmit}>
                    确定
                  </Button>,
                ]
          }
        >
          {/* {!isEvent ? <Form style={{ marginLeft: 16 }}> */}

          {/*    {this.labelView(false, (isProp || isEvent), type)} */}
          {/*    {(isProp || isEvent) && this.labelView(true, isProp, type)} */}

          {/*    {(type === 1 || type === 4 || type === 5) && this.relationView()} */}
          {/*  </Form> : */}
          <Form style={{ marginLeft: 16 }}>
            {type !== 3 ? (
              <>
                <Steps style={{ margin: '10px 110px', width: 500 }} current={current}>
                  {steps.map((item) => (
                    <Step key={item.title} title={item.title} />
                  ))}
                </Steps>
                <div style={{ marginTop: 10, overflow: 'hidden', paddingLeft: 10, paddingRight: 10 }}>
                  {steps[current].content}
                </div>
              </>
            ) : (
              eventElementMap
            )}
          </Form>
          {/* } */}
        </Modal>
      </span>
    )
  }
}

const Config = Form.create()(Edit)

export default Config
